package com.example.presentshopping.ui.activity

import android.app.Dialog
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.text.TextUtils
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import android.widget.ImageView
import androidx.fragment.app.FragmentActivity
import com.example.presentshopping.R
import com.example.presentshopping.config.base.BaseMvpActivity
import com.example.presentshopping.config.bean.AlipayBean
import com.example.presentshopping.jpay.JPay
import com.example.presentshopping.mvp.presenter.PublicPresenter
import com.example.presentshopping.net.http.HttpRequest
import com.example.presentshopping.net.http.HttpURL
import com.example.presentshopping.net.http.HttpURL.Req_aliRecharge
import com.example.presentshopping.net.observer.TaskCallback
import com.example.presentshopping.ui.custom.PayPwdEditText
import com.example.presentshopping.ui.dialog.MessageDialog
import com.example.presentshopping.utils.ToastUtil
import com.example.presentshopping.utils.tool.GsonUtils
import kotlinx.android.synthetic.main.activity_gold_s.*
import kotlinx.android.synthetic.main.activity_gold_s.button3
import kotlinx.android.synthetic.main.activity_gold_s.editTexnName

class GoldSActivity : BaseMvpActivity() {
    private var walletDialog: Dialog? = null
    var sendMesPresenter: PublicPresenter? = null
    var aliPayBean : AlipayBean?=null
    var pay = 1
    override val layoutId: Int
        get() = R.layout.activity_gold_s

    override fun initView(savedInstanceState: Bundle?) {
        sendMesPresenter = PublicPresenter(this, false, "")
        sendMesPresenter?.attachView(this)
        title_main_tv.leftBackImageTv.setOnClickListener { finish() }
        click_nowPay.setOnClickListener {
            is_nowPay.visibility = View.VISIBLE
            is_alipay.visibility = View.GONE
            pay = 2
        }
        click_alipay.setOnClickListener {
            is_nowPay.visibility = View.GONE
            is_alipay.visibility = View.VISIBLE
            pay = 1
        }
        button3.setOnClickListener {
            if (!TextUtils.isEmpty(editTexnName.text)) {
                when (pay) {
                    1 -> { setalipay(editTexnName.text.toString()) }
                    2 -> { showEditPayPwdDialog(editTexnName.text.toString()) }
                }
            } else {
                showToast("请输入兑换数量")
            }
        }


    }

    override fun onDestroy() {
        sendMesPresenter?.detachView()
        super.onDestroy()

    }

    override fun showToast(msg: String?) {
        ToastUtil.showMsg(msg)
    }

    override fun onFailure(e: Throwable?, code: Int, msg: String?, isNetWorkError: Boolean) {

    }

    override fun onSuccess(data: String?) {

    }

    //平台支付
    fun showEditPayPwdDialog(order_id: String) {
        val view: View = layoutInflater.inflate(R.layout.dialog_layout, null)
        walletDialog = Dialog(this, R.style.walletFrameWindowStyle)
        walletDialog!!.setContentView(
            view, ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT
            )
        )

        val window = walletDialog!!.window
        val wl = window!!.attributes

        //紧贴软键盘弹出
        wl.gravity = Gravity.BOTTOM
        // 以下这两句是为了保证按钮可以水平满屏
        wl.width = ViewGroup.LayoutParams.MATCH_PARENT
        wl.height = ViewGroup.LayoutParams.WRAP_CONTENT
        walletDialog!!.onWindowAttributesChanged(wl)
        walletDialog!!.setCanceledOnTouchOutside(false)
        walletDialog!!.show()
        //忘记密码 按钮
        view.findViewById<View>(R.id.tv_forgetPwd).setOnClickListener {
            startActivity(
                Intent(
                    this@GoldSActivity,
                    SetupPayPwdCheckActivity::class.java
                )
            )
        }
        val ppet: PayPwdEditText = view.findViewById(R.id.dialog_ppet)
        val img_cancle = view.findViewById<ImageView>(R.id.img_cancle)
        //调用initStyle方法创建你需要设置的样式
        //调用initStyle方法创建你需要设置的样式
        ppet.initStyle(R.drawable.edit_num_bg, 6, 0.33f, R.color.gray, R.color.black, 30)
        img_cancle.setOnClickListener {
            walletDialog!!.dismiss()
            //手动收起软键盘
            val imm =
                getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
            imm.hideSoftInputFromWindow(ppet.windowToken, 0)
            imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS)

        }

        ppet.setOnTextFinishListener {
            //密码输入完后的回调
            walletDialog!!.dismiss()
            //手动收起软键盘
            val imm = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
            imm.hideSoftInputFromWindow(ppet.windowToken, 0)
            //可在此执行下一步操作
            val paypass = ppet.pwdText
            order_id?.let { it1 -> setBitMap(it1, paypass) }

        }
        //延迟弹起软键盘，使PayPwdEditText获取焦点
        Handler().postDelayed({ ppet.setFocus() }, 100)

    }
    fun setBitMap(amount: String, password: String) {
        sendMesPresenter?.netWorkRequestPost(HttpURL.Req_balanceChange,
            HttpRequest.getInvitationCode(amount, password), object : TaskCallback {
                override fun onSuccess(data: String?) {
                    setDialog("兑换成功", "继续兑换")
                }

                override fun onFailure(
                    e: Throwable?,
                    code: Int,
                    msg: String?,
                    isNetWorkError: Boolean
                ) {
                    showToast(msg)
                }

            })
    }
    fun setDialog(text: String?, Confirm: String?) {
        MessageDialog.Builder(context as FragmentActivity?)
            .setTvTitle("")
            .setTitle("")
            .setMessage(text)
            .setConfirm(Confirm)
            .setCancel("退出")
            .setListener(object : MessageDialog.OnListener {
                override fun onConfirm(dialog: Dialog?) {

                }

                override fun onCancel(dialog: Dialog?) {
                    finish()
                }

            }).show()

    }

  fun setalipay(orderid: String){
      sendMesPresenter?.netWorkRequestPost(Req_aliRecharge ,HttpRequest.waitChange("amount",orderid),object :TaskCallback{
          override fun onSuccess(data: String?) {
              aliPayBean = GsonUtils.getGson().fromJson(data, AlipayBean().javaClass)
              aliPay(aliPayBean?.data!!)
          }

          override fun onFailure(e: Throwable?, code: Int, msg: String?, isNetWorkError: Boolean) {

          }

      })

  }
    private fun aliPay(orderInfo: String) { // 支付宝支付
        JPay.getIntance(this).toPay(JPay.PayMode.ALIPAY, orderInfo, object : JPay.JPayListener {

            override fun onPaySuccess(resultStatus: String?) {
                setDialog("兑换成功", "继续兑换")
            }

            override fun onPayError(error_code: Int, message: String) {
                showToast("支付失败")
                //  finish()
            }

            override fun onPayCancel() {
                showToast("取消了支付")
                //  finish()
            }
        })
    }



}